#include "fsm.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        fprintf(stderr, "copy; Usage: %s source_file dst_file\n", argv[0]);
        exit(1);
    }

    int src = open(argv[1], O_RDONLY | O_NONBLOCK);

    if (src < 0)
    {
        perror("open()");
        exit(1);
    }

    int dst = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, 0755);
    if (dst < 0)
    {
        perror("open()");
        exit(1);
    }

    fsm_st fsm = fsm_new(src, dst);
    while (fsm_state(fsm) != STATE_T)
    {
        fsm_drive(fsm);
    }

    const char *err = fsm_error(fsm);

    if (err != NULL)
    {
        fprintf(stderr, "%s", err);
    }

    fsm_close(fsm);
    close(src);
    close(dst);
    exit(0);
}